import React, {useEffect, useState} from 'react';
import axios from 'axios';
import {Link} from "react-router-dom";
import './friendly.css'
import LoadingSpinner from "../components/LoadingSpinner";
import InlineError from "../components/InlineError";
import * as errmsg from '../constants'

export default function PostDetail({ slug }) {
    const [loading, setLoading] = useState(true)
    const [post, setPost] = useState({})
    const [error, setError] = useState('')

    const url = `/api/v1/posts/${slug}/`

    useEffect(() => {
        axios.get(url)
            .then(response => {
                setLoading(false)
                setPost(response.data)
                setError('')
            })
            .catch(err => {
                setLoading(false)
                setPost({})
                setError(errmsg.CUSTOM_ERROR_MSG)
            })
    }, [url])  // slug改变时重新加载页面

    if (loading) return <LoadingSpinner/>
    if (error) return <InlineError error={error}/>

    return (
        <div className="col-md-8">
            <div>
                <h1 className="card-title detail-post-title">{post.title}</h1>

                <p className="card-text post-meta">
                    发布于: {post.pub_date} | 阅读: {post.num_views} | 标签:
                    {!!post.tags && post.tags.map(tag => (
                        <Link to={`/tag/${tag}`} key={tag} className="mx-2 post-tag font-weight-light">#{tag}</Link>
                    ))}
                </p>

                <p>{post.subtitle}</p>
                <hr/>

                <p style={{marginTop: "2rem"}} dangerouslySetInnerHTML={{__html: post.content}}/>

                <nav className="blog-pagination d-flex justify-content-between page-nav mt-5">
                    {post.next_post ? (
                        <Link className="text-decoration-none ms-auto"
                              to={`/post/${post.next_post.slug}`} tabIndex="-1" data-toggle="tooltip"
                              data-placement="right" title="下一篇">
                            {post.next_post.title}
                            <svg width="1em" height="1em" viewBox="0 0 16 16"
                                 className="bi bi-chevron-double-right" fill="currentColor"
                                 xmlns="http://www.w3.org/2000/svg">
                                <path fillRule="evenodd"
                                      d="M3.646 1.646a.5.5 0 0 1 .708 0l6 6a.5.5 0 0 1 0 .708l-6 6a.5.5 0 0 1-.708-.708L9.293 8 3.646 2.354a.5.5 0 0 1 0-.708z"/>
                                <path fillRule="evenodd"
                                      d="M7.646 1.646a.5.5 0 0 1 .708 0l6 6a.5.5 0 0 1 0 .708l-6 6a.5.5 0 0 1-.708-.708L13.293 8 7.646 2.354a.5.5 0 0 1 0-.708z"/>
                            </svg>
                        </Link>
                    ) : null}
                </nav>
            </div>
        </div>
    );
};
